<template>
  <!--  break规则模板 -->
  <div>
    <!-- 按钮与搜索 -->
    <el-row class="sceneManager container">
      <el-col style="margin-right: 10px" class="content-left">
        <!-- 操作区域 -->
        <upper-template
          :configIcon="false"
          @search="(searchForm.page = 1), searchFunc()"
          @clear="
            (searchForm.sceneCode = ''),
            (searchForm.sceneName = '')
          "
        >
          <!-- 操作按钮区 -->
          <template slot="buttonArea" >
            <el-button @click="addOrEditFunc('1')">新增</el-button>
            <el-button @click="editFunc('2')">编辑</el-button>
            <el-button @click="delFunc()">删除</el-button>
            <el-button @click="editFunc('3')">查看</el-button>
            <el-button @click="editFunc('5')">复制</el-button>
            <el-button @click="addOrEditFunc('4')">查看历史</el-button>
          </template>
          <!-- 搜索区 -->
          <template slot="searchArea">
            <el-form
              :model="searchForm"
              ref="searchForm"
              label-width="107px"
              label-position="left"
              size="mini"
            >
              <el-form-item label="情景编码：">
                <el-input
                  v-model="searchForm.sceneCode"
                  style="width: 150px"
                ></el-input>
              </el-form-item>
              <el-form-item label="情景名称：">
                <el-input
                  v-model="searchForm.sceneName"
                  style="width: 150px"
                ></el-input>
              </el-form-item>
            </el-form>
          </template>
        </upper-template>
        <!-- 列表 -->
        <el-table
          ref="multipleTable"
          :data="tableData"
          style="width: 100%"
          @row-click="authorizeFor"
        > 
          <el-table-column prop="sceneId" align="center" header-align="center"
					:filter-multiple="true" type="selection">
				  </el-table-column>
				  <el-table-column label="情景编码" prop="sceneCode" align="center" header-align="center"
					:filter-multiple="true" :show-overflow-tooltip="true">
				  </el-table-column>
          <el-table-column label="情景名称" prop="sceneName" align="center" header-align="center"
					:filter-multiple="true" :show-overflow-tooltip="true">
				</el-table-column>
				<el-table-column label="定价方法" prop="methodComment" align="center" header-align="center"
					:filter-multiple="true" :show-overflow-tooltip="true">
				</el-table-column>
				<el-table-column label="定价曲线" prop="curveComment" align="center" header-align="center"
					:filter-multiple="true" :show-overflow-tooltip="true">
				</el-table-column>
				<el-table-column label="调整项" prop="adjComment" align="center" header-align="center"
					:filter-multiple="true" :show-overflow-tooltip="true">
				</el-table-column>
				<el-table-column label="是否默认" prop="defaultFlag" align="center" header-align="center"
					:filter-multiple="true">
					<template slot-scope="scope">
						<span v-if="scope.row.defaultFlag==1"> 是 </span>
						<span v-if="scope.row.defaultFlag==0"> 否 </span>
					</template>
				</el-table-column>
				<el-table-column label="是否BREAKFUNDING" prop="fundingFlag" align="center"
					header-align="center" :filter-multiple="true">
					<template slot-scope="scope">
						<span v-if="scope.row.fundingFlag==1"> 是 </span>
						<span v-if="scope.row.fundingFlag==0"> 否 </span>
					</template>
				</el-table-column>
				<el-table-column label="是否BREAKCHARGE" prop="chargeFlag" align="center"
					header-align="center" :filter-multiple="true">
					<template slot-scope="scope">
						<span v-if="scope.row.chargeFlag==1"> 是 </span>
						<span v-if="scope.row.chargeFlag==0"> 否 </span>
					</template>
				</el-table-column>
				<el-table-column label="是否单笔定价" prop="accountFlag" align="center" header-align="center"
					:filter-multiple="true">
					<template slot-scope="scope">
						<span v-if="scope.row.accountFlag==1"> 是 </span>
						<span v-if="scope.row.accountFlag==0"> 否 </span>
					</template>
				</el-table-column>
          <el-table-column
            prop="creator"
            label="创建人"
            :show-overflow-tooltip="true"
          ></el-table-column>
          <el-table-column
            prop="createdTm"
            :show-overflow-tooltip="true"
            label="创建时间"
            sortable
          >
            <template slot-scope="scope">
              <div v-if="scope.row.createdTm">
                {{ timeFormat(scope.row.createdTm) }}
              </div>
              <div v-else>-</div>
            </template>
          </el-table-column>
          <el-table-column
            prop="modifier"
            :show-overflow-tooltip="true"
            label="修改人"
            sortable
            :formatter="(row) => row.modifier || '-'"
          >
          </el-table-column>
          <el-table-column
            prop="modifiedTm"
            :show-overflow-tooltip="true"
            label="修改时间"
            sortable
          >
            <template slot-scope="scope">
              <div v-if="scope.row.createdTm">
                {{ timeFormat(scope.row.modifiedTm) }}
              </div>
              <div v-else>-</div>
            </template>
          </el-table-column>
          <el-table-column label="情景描述" prop="sceneDes" align="center" header-align="center"
					:filter-multiple="true" :show-overflow-tooltip="true">
				</el-table-column>
				<el-table-column label="版本" prop="versionNum" align="center" header-align="center"
					:filter-multiple="true">
				</el-table-column>
        </el-table>
        <pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="searchForm.page"
          :page-size="searchForm.size"
          @refresh="searchFunc"
          :total="total"
        ></pagination>
      </el-col>
    </el-row>
    <!-- 新增、编辑弹窗 -->
    <el-dialog
      v-dialogDrag
      :title="titleName"
      :visible.sync="sceneAddAndEditDi"
      :modal-append-to-body="false" 
      :lock-scroll="false" 
      :show-close="true" 
      width="1000px"
      top="2%"
    >
      <el-form
        :model="saveRuleForm"
        ref="saveRuleForm"
        label-width="120px"
        label-position="right"
        :rules="saveRuleFormRules"
        :close-on-click-modal="false" 
        :close-on-press-escape="false"
      >
        <el-row :gutter="20" type="flex">
					<el-col>
						<div>
							<el-form-item label="情景编码" prop="sceneCode" >
								<el-input event-render="loadText" v-model="saveRuleForm.sceneCode" type="text"
									:disabled="false">
								</el-input>
							</el-form-item>
						</div>
					</el-col>
					<el-col>
						<div>
							<el-form-item label="情景名称" prop="sceneName" >
								<el-input event-render="loadText" v-model="saveRuleForm.sceneName" type="text"
									:disabled="false">
								</el-input>
							</el-form-item>
						</div>
					</el-col>
				</el-row>
        <el-row :gutter="20" type="flex">
					<el-col>
						<div>
							<el-form-item label="默认情景" prop="defaultFlag">
								<el-checkbox v-model="saveRuleForm.defaultFlag" :checked="false" true-label="1" @click="checkDefaultFlag"
									false-label="0" >
								</el-checkbox>
							</el-form-item>
						</div>
					</el-col>
					<el-col>
						<div>
							<el-form-item label="情景描述" prop="sceneDes">
								<el-input event-render="loadText" v-model="saveRuleForm.sceneDes" type="textarea"
									:disabled="false">
								</el-input>
							</el-form-item>
						</div>
					</el-col>
				</el-row>
      </el-form>
      <div style="height:400px;overflow:scroll;">
      <el-row>
			  <el-col>
					<el-tabs ref="tab" type="border-card" value="methodRuleGroup" v-model="activeName">

						<el-tab-pane label="定价规则" name="methodRuleGroup">
              <el-row>
                <el-col :span="6">
                  <el-table ref="methodRuleTableRef" :data="methodRuleGroupList" height="20em"
                    @selection-change="changeMethodTableFun" size="medium" >
                    <el-table-column label="请选择定价方法规则组" prop="ruleGroupName" :filter-multiple="true">
                    </el-table-column>
                    <el-table-column prop="methodRuleGroup" align="center" header-align="center"
                      @selection-change="changeMethodTableFun" :filter-multiple="true"
                      type="selection">
                    </el-table-column>
                  </el-table>
                </el-col>
              </el-row>
						</el-tab-pane>

						<el-tab-pane label="曲线规则" name="curveRuleGroup">
              <el-row>
                <el-col :span="6">
                  <el-table ref="curveRuleTableRef" :data="curveRuleGroupList" height="20em"
                    @selection-change="changeCurveTableFun" size="medium" >
                    <el-table-column label="请选择定价曲线规则组" prop="ruleGroupName" :filter-multiple="true">
                    </el-table-column>
                    <el-table-column prop="curveRuleGroup" align="center" header-align="center"
                      @selection-change="changeCurveTableFun" :filter-multiple="true"
                      type="selection">
                    </el-table-column>
                  </el-table>
                </el-col>
              </el-row>
						</el-tab-pane>

            <el-tab-pane label="调整项" name="adjustDefinition">
							<el-form ref="paramFormAdj" :model="saveRuleForm" tokenKey="paramFormAdj"
								:rules="saveRuleFormRules" label-width="20em">
								<div v-for="(adj,index) in adjList" :key="index">
									<el-row >
										<el-col :span="10.5">
											<el-form-item :label="adj.adjName" prop="ruleGroupId" >
                        <el-select
                        v-model="adj.ruleGroupId"
                        placeholder="请选择"
                        style="width: 65%"
                        @change="changeAdjFun(adj)"
                        :disabled="ruleOperateType == 3"
                        >
                        <el-option
                            v-for="(item,i) in adj.adjGroupList"
                            :key="i"
                            :label="item.ruleGroupName"
                            :value="item.adjRuleGroup"
                        ></el-option>
                      </el-select>
											</el-form-item>
										</el-col>
									</el-row>
								</div>

								<div>
									<el-row :gutter="20" type="flex">
										<el-col :span="10">
											<el-form-item label="调整项互斥配置：" prop="reserveAdj" >
											</el-form-item>
										</el-col>
									</el-row>
									<el-row >
										<el-col  :span="11">
											<el-form-item label="保留调整项" prop="reserveAdj" >
												<el-select ref="reserveAdjRef" v-model="reserveAdjValue" multiple
													@change="reserveAdjChange" placeholder="请选择..." :loading="false"
													popper-append-to-body style="position:relative" >
													<el-option 
                          :label="item.adjName" 
                          :value="item.adjId" 
                          tdList="reserveAdjDatas"
													v-for="(item,i) in reserveAdjDatas" 
                          :key="i">
													</el-option>
												</el-select>
											</el-form-item>
										</el-col>
										<el-col  :span="11">
											<el-form-item label="被斥调整项" prop="excludeAdj" >
												<el-select ref="excludeAdjRef" v-model="excludeAdjValue" multiple
													@change="excludeAdjChange" placeholder="请选择..." :loading="false"
													popper-append-to-body style="position:relative" >
													<el-option :label="item.adjName" :value="item.adjId" tdList="excludeAdjDatas"
														v-for="(item,i) in excludeAdjDatas" :key="i">
													</el-option>
												</el-select>
											</el-form-item>
										</el-col>
									</el-row>
								</div>
							</el-form>
						</el-tab-pane>

            <el-tab-pane label="其他规则" name="otherRule">
							<el-form ref="paramFormAdj" :model="saveRuleForm" tokenKey="paramFormAdj"
								:rules="saveRuleFormRules" label-suffix="：" label-width="8em">
								<el-row :gutter="20">
									<el-col>
										<el-form-item label="计算BreakFunding" prop="fundingFlag" label-width="14em"
											required>
											<el-checkbox v-model="saveRuleForm.fundingFlag" true-label="1" false-label="0"
												:checked="saveRuleForm.fundingFlag==1">
											</el-checkbox>
										</el-form-item>
									</el-col>
									<!--col,18-->
								</el-row>
								<el-row :gutter="20" >
									<el-col>
										<el-form-item label="计算BreakCharge" prop="chargeFlag" label-width="14em"
											required>
											<el-checkbox v-model="saveRuleForm.chargeFlag" true-label="1" false-label="0"
												:checked="saveRuleForm.chargeFlag==1">
											</el-checkbox>
										</el-form-item>
									</el-col>
								</el-row>
                <el-row :gutter="20">
									<el-col>
										<el-form-item label="计算组合定价" prop="combinationFlag" label-width="14em"
											required>
											<el-checkbox v-model="saveRuleForm.combinationFlag" true-label="1" false-label="0"
												:checked="saveRuleForm.combinationFlag==1">
											</el-checkbox>
										</el-form-item>
									</el-col>
								</el-row>
								<el-row :gutter="20">
									<el-col>
										<el-form-item label="计算单账户定价" prop="accountFlag" label-width="14em"
											required>
											<el-checkbox v-model="saveRuleForm.accountFlag" true-label="1" false-label="0"
												:checked="saveRuleForm.accountFlag==1">
											</el-checkbox>
										</el-form-item>
									</el-col>
								</el-row>
							</el-form>
						</el-tab-pane>
						  
					</el-tabs>
			  </el-col>
			</el-row>
      </div>  
      
      <div slot="footer" v-if="ruleOperateType != '3'">
         <el-button @click="saveFunc">确 定</el-button>
         <el-button @click="sceneAddAndEditDi = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 新增、编辑弹窗 -->
    <!-- 查看历史弹窗 --> 
    <el-dialog
      v-dialogDrag
      title="历史信息查询页面"
      :visible.sync="historyVisible"
      width="60%"
      top="2%"
    >
      <historyTable
        :tableData="tableDataH"
        :total="totalH"
        @handleSizeChange="handleSizeChangeH"
        @handleCurrentChange="handleCurrentChangeH"
        @searchFunc="getTableDataHistory"
      ></historyTable>
    </el-dialog>
    <!--  查看历史弹窗 -->
  </div>
</template>

<script>
import { ruleTemplate,curveRule,adjRule,sceneManage } from "@/api/index";
import upperTemplate from "@/components/upperTemplate.vue";
import { getDict } from "@/api/getDict";
// 引入查看历史
import historyTable from "../sceneManage/sceneManage_history";
import moment from "moment";
export default {
  //定义数据
  data() {

    //校验方法区
    var sceneCodeFun = (rule, value, callback) => {
      value=value.replace(/(^\s*)|(\s*$)/g, "");
      if(!/^[a-zA-Z0-9_]{1,40}$/.test(value)){
        return callback(new Error("只可输入(1-40)位的英文字母、数字和下划线！"));
      }
      
      if(value){
          let data = {
            sceneCode: value,
            operateType: this.ruleOperateType
          };
          sceneManage.checkSceneCodeUnique(data).then(res => {
            if (res.code === 200) {
              if(res.data == "1") {
                callback(new Error("此情景编号已存在，无法使用！"));
              } else {
                callback();
              }
            }
          });
              
      }else callback();
    };
    
    var sceneNameFun = (rule, value, callback) => {
    	value=value.replace(/(^\s*)|(\s*$)/g, "");
      var zhLen = value.replace(/[^\u4e00-\u9fa5]/g, "").length;
      var length = value.length - zhLen + zhLen * 3;
      var result = length - 20;
      if(result > 0){ 
        return callback(new Error("输入字符超过数据库设定最大长度!"));
      }else if(!/^[a-zA-Z0-9_\u4e00-\u9fa5]+$/.test(value)){
        return callback(new Error("只可输入字母汉字数字_！"));
      }
    	
    	if(value){
			 let data = {
          sceneCode: this.saveRuleForm.sceneCode,
          sceneName: value,
          operateType: this.ruleOperateType
        };
        sceneManage.checkSceneNameUnique(data).then(res => {
          if (res.code === 200) {
            if(res.data == "1") {
              callback(new Error("此情景名称已存在，无法使用！"));
            } else {
              callback();
            }
          }
        });
      }else callback();
    };




    return {
      activeName: 'methodRuleGroup',//默认选中 定价方法tab页
      sceneCode:'',//搜索参数
      sceneName:'',//搜索参数
      sceneStatus:'1',//首页查看列表数据参数
      searchForm: {
        sceneCode:'',//搜索参数
        sceneName:'',//搜索参数
        sceneStatus:'1',
        page: 1,
        size: 15,
      },
      ruleOperateType: "",
      total: 0,
      titleName: "",
      
      headData: {},
      tableData: [],

      sceneAddAndEditDi: false,
      methodRuleGroupList:[],//定价方法规则组
      curveRuleGroupList:[],//定价曲线规则组
      adjList:[],
	    adjListLength:'',// 调整项数组长度
      adjRuleGroupList:[],//调整项组
      orderNumList:[],
      ruleModeltypes:[],

      multipleSelection:[],
      reserveAdjDatas:[],
      excludeAdjDatas:[],
      reserveAdjValue:[],
      excludeAdjValue:[],

      saveRuleForm: {
       sceneCode:'',
    	 sceneName:'',
    	 versionNum:'1',
    	 sceneStatus:'1',
    	 sceneDes:'',
    	 methodRuleGroup:[],
    	 curveRuleGroup:[],
    	 sceneId:'',
    	 defaultFlag:'0',

    	 adjRuleDatas:[],
       excludeAdjDatas:[],
       priceRuleDatas:[],
       reserveAdjDatas:[],

    	 fundingFlag:'0',
    	 chargeFlag:'0',
    	 accountFlag:'0',
    	 reserveAdj:'',//保留调整项
    	 excludeAdj:'',//被斥调整项
    	 formationFlag:'0',
    	 combinationFlag:'0',
        
      },
       
      //表单字段规则校验
      saveRuleFormRules: {
       sceneCode: [{ required: true, message: '此项为必输项', trigger: 'blur' },
    		{ validator: sceneCodeFun, trigger: "blur" }],
    	 sceneName: [{ required: true, message: '此项为必输项', trigger: 'blur' },
    		{ validator: sceneNameFun, trigger: "blur" }],
        
      },

       //查询历史弹窗
      historyVisible: false,
      tableDataH: [],
      headDataH: {},
      rowHistory: {},
      pageH: 1,
      sizeH: 15,
      totalH: 0 



    };
  },
  //组件引入
  components: {
    upperTemplate,
    historyTable
  },
  //创建初始化
  created() {
    this.searchFunc();
    this.getMethodRuleGroupList();
    this.getCurveRuleGroupList();
    this.getOrderNumList();
    
    
  },
  mounted() {

    if (this.sceneAddAndEditDi) {
      this.$nextTick(() => {
        this.emptydataTableForm();
      });
    }
  },
  //监控数值变化
  watch: {
   
  },
  //运算
  computed: {},
  methods: { 
      
    //   点击行选中
    authorizeFor(row) {
      if (this.$refs.multipleTable) {
        this.$refs.multipleTable.clearSelection();
      }
      this.$refs.multipleTable.toggleRowSelection(row, true);
    },
    
    //查询数据
    searchFunc() {
          sceneManage.findAll(this.searchForm).then((res) => {
            if (res.code == 200) {
              this.tableData = res.datas.rows;
              this.total = res.datas.total;
            }
          });
    },
  
     
    //事件转换
    timeFormat(val) {
      if (val) return moment(val).format("YYYY-MM-DD HH:mm:ss");
      else return "";
    },
    timeFormatShort(val) {
      if (val) return moment(val).format("YYYY-MM-DD");
      else return "";
    },
    //页码值改变
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.searchForm.size = val;
      this.searchFunc();
    },
    //当前页改变
    handleCurrentChange(val) {
      this.searchForm.page = val;
      console.log(`当前页: ${val}`);
      this.searchFunc();
    },
    //页码值改变
    handleSizeChangeH(val) {
      this.sizeH = val;
      this.getTableDataHistory();
    },
    //当前页改变
    handleCurrentChangeH(val) {
      this.pageH = val;
      console.log(`当前页: ${val}`);
      this.getTableDataHistory();
    },
    emptydataTableForm() {
      //清空上次显示的值
      this.saveRuleForm = {};
      this.$set(this.saveRuleForm,"sceneCode", "");
      this.$set(this.saveRuleForm, "sceneName", "");
      this.$set(this.saveRuleForm, "sceneId", "-");
      this.$set(this.saveRuleForm, "sceneDes", "");
      this.reserveAdjValue = [];
      this.excludeAdjValue = [];


    	 this.$set(this.saveRuleForm, "defaultFlag", "0");
       this.$set(this.saveRuleForm, "fundingFlag", "0");
    	 this.$set(this.saveRuleForm, "chargeFlag", "0");
    	 this.$set(this.saveRuleForm, "accountFlag", "0");
    	 this.$set(this.saveRuleForm, "formationFlag", "0");
    	 this.$set(this.saveRuleForm, "combinationFlag", "0");

        this.$set(this.saveRuleForm, "methodRuleGroup", []);
        this.$set(this.saveRuleForm, "curveRuleGroup", []);
        this.$set(this.saveRuleForm, "priceRuleDatas", []);

        this.reserveAdjDatas = [];
        this.excludeAdjDatas = [];
        this.$set(this.saveRuleForm, "reserveAdj", []);
        this.$set(this.saveRuleForm, "excludeAdj", []);
        this.getReserveAdjData();
    },
    //新增弹窗
    addOrEditFunc(val) {
      this.ruleOperateType = val;

      if (this.ruleOperateType === "1") {
        this.getAdjList();
        this.titleName = "新增情景管理";
        this.activeName = 'methodRuleGroup';
        this.sceneAddAndEditDi = true;
        
        this.$nextTick(() => {
          //清除校验结果
          this.$refs.saveRuleForm.clearValidate();
          this.$refs.saveRuleForm.resetFields();
          this.$refs.methodRuleTableRef.clearSelection();
          this.$refs.curveRuleTableRef.clearSelection();
          //清空表单
          this.emptydataTableForm();
        });

      } else if (this.ruleOperateType === "4") {
        let selection = this.$refs.multipleTable.selection;
        if (selection.length < 1) {
          return this.$message.warning("请选择一条数据");
        } else if (selection.length > 1) {
          return this.$message.warning("只能选择一条数据");
        } else  {
          //查看历史页面
          this.historyVisible = true;
          this.rowHistory = selection[0];
          // 获取历史页面数据
          this.getTableDataHistory();
        }
      }
    },

    editFunc(val) {
        this.getAdjList();
        this.reserveAdjValue = [];
        this.excludeAdjValue = [];
        this.reserveAdjDatas = [];
        this.excludeAdjDatas = [];
        this.saveRuleForm.reserveAdj=[];
        this.saveRuleForm.excludeAdj=[];

        this.ruleOperateType = val;
        this.activeName = 'methodRuleGroup';
        if(this.ruleOperateType == "2"){
          this.titleName = "编辑情景管理";
        } else if(this.ruleOperateType == "3"){
          this.titleName = "查看情景管理";
        } else {
          this.titleName = "复制情景管理";
        }
          let selection = this.$refs.multipleTable.selection;
          if (selection.length < 1) {
            return this.$message.warning("请选择一条数据");
          } else if (selection.length > 1) {
            return this.$message.warning("只能选择一条数据");

          } else {
            this.saveRuleForm.sceneId = selection[0].sceneId;
            this.sceneAddAndEditDi = true; 
            this.saveRuleForm = Object.assign({},this.saveRuleForm,selection[0]);
            let priceRuleDatas = this.saveRuleForm.priceRuleDatas;
            
            let list =[];
            //定价方法规则 赋值
            for(let i =0;i<this.methodRuleGroupList.length;i++){
                for(let j =0;j<priceRuleDatas.length;j++){
                  if(priceRuleDatas[j].ruleType=='1'){
                    if(this.methodRuleGroupList[i].methodRuleGroup==priceRuleDatas[j].ruleGroupId){
                      list.push(this.methodRuleGroupList[i]);
                    }
                  }
                }
            }
            this.$nextTick(()=>{
              for(let i=0;i<list.length;i++){
                  this.$refs.methodRuleTableRef.toggleRowSelection(list[i],true)
              }
            });

            //定价曲线规则 赋值
            let list2 = [];
            for(let i =0;i<this.curveRuleGroupList.length;i++){
                for(let j =0;j<priceRuleDatas.length;j++){
                  if(priceRuleDatas[j].ruleType=='2'){
                    if(this.curveRuleGroupList[i].curveRuleGroup==priceRuleDatas[j].ruleGroupId){
                      list2.push(this.curveRuleGroupList[i]);
                    }
                  }
                }
            }
            this.$nextTick(()=>{
              for(let i=0;i<list2.length;i++){
                  this.$refs.curveRuleTableRef.toggleRowSelection(list2[i],true);
              }
            });
           
            //处理调整项规则 赋值
            let rtndatas  = selection[0].adjRuleDatas;
            adjRule.findAdjDefList().then((res) => {
                if (res.code == 200) {
                    this.adjList = res.datas;
                    for (let i =0;i<this.adjList.length;i++){
                      let value = this.adjList[i];
                      //获取调整项 选中的值
                      let flag=true;
                      for(let j=0;j<rtndatas.length;j++){
                        if(value.adjId === rtndatas[j].adjId){
                          value.ruleGroupId = rtndatas[j].ruleGroupId;
                          this.changeAdjFun(value);
                          flag=false;
                        }
                      }
                      if(flag===true){
                          value.ruleGroupId='-1';
                      }
                    }
                }
            });

            //保留调整项 赋值
            this.getReserveAdjData();
          }
    },

    //获取定价方法规则组数据
    getMethodRuleGroupList(){
      ruleTemplate.findAllList_mtdRlGrp().then((res) => {
          if (res.code == 200) {
            this.methodRuleGroupList = res.datas;
          }
      });

    },
    //获取定价曲线规则组数据
    getCurveRuleGroupList(){
      curveRule.findAll_grp().then((res) => {
          if (res.code == 200) {
            this.curveRuleGroupList = res.datas;
          }
      });
    },
    //校验系统中是否存在默认情景
    checkDefaultFlag(){
      
    },
    //定价方法规则表格复选框改变时触发
    changeMethodTableFun(val){
    let multipleSelection = [];
        for (let i = 0; i < val.length; i++) {
            if (multipleSelection.indexOf(val[i].methodRuleGroup) === -1) {
                multipleSelection.push(val[i].methodRuleGroup)
            }
        }
      this.saveRuleForm.methodRuleGroup=multipleSelection;
    },

    reserveAdjChange(val){
      this.saveRuleForm.reserveAdj = val.join();
    },
    excludeAdjChange(val){
      this.saveRuleForm.excludeAdj = val.join();
    },
    //定价曲线规则表格复选框改变时触发
    changeCurveTableFun(val){
      let multipleSelection = [];
        for (let i = 0; i < val.length; i++) {
            if (multipleSelection.indexOf(val[i].curveRuleGroup) === -1) {
                multipleSelection.push(val[i].curveRuleGroup)
            }
        }
      this.saveRuleForm.curveRuleGroup=multipleSelection;
    },   
 
    getOrderNumList(){
      getDict("ftp_order_num").then((res) => {
        if (res.code == 200) {
          this.orderNumList = res.datas;
        } else {
          this.$message.error(res.message);
        }
      });
    },
    getAdjList(){
      adjRule.findAdjDefList().then((res) => {
         if (res.code == 200) {
          this.adjList = res.datas;
          console.log(this.adjList,"---this.adjList-111111-");
          for (let i =0;i<this.adjList.length;i++){
              this.adjList[i].ruleGroupId='-1';

              let data = {
                adjId:this.adjList[i].adjId,
                sceneId:this.saveRuleForm.sceneId
              }
              adjRule.findAdjRuleGroupList4Combox(data).then((res) => {
                if (res.code == 200) {
                  this.adjList[i].adjGroupList = res.datas;
                  console.log(this.adjList[i].adjGroupList,"---this.adjList[i].adjGroupList----");
                  this.$forceUpdate();
                }  
              }); 
          }
         }
      });  
    },
    //获取表单中保留调整项、被斥调整项数据
    getReserveAdjData(){
      sceneManage.findSceneAdjListBySceneId({sceneId:this.saveRuleForm.sceneId}).then((res) => {
            if (res.code == 200) {
              let data = res.datas;
              this.reserveAdjDatas = data;
              this.excludeAdjDatas = data;
 
              for(let i=0;i<data.length;i++){
                if(data[i].reserveFlag=="1"){
                  this.reserveAdjValue.push(data[i].adjId);
                }
                if(data[i].excludeFlag=="1"){
                  this.excludeAdjValue.push(data[i].adjId);
                }
              }
              this.saveRuleForm.reserveAdj=this.reserveAdjValue.join();
              this.saveRuleForm.excludeAdj=this.excludeAdjValue.join();
            }
      });
      
    },
    changeAdjFun(adj){
      this.$forceUpdate()
		  let sceneId=this.saveRuleForm.sceneId;
	    let adjId2 = adj.adjId; //获取调整项id
	    let adjName = adj.adjName; //获取调整项名称
	      
	    if(adj.ruleGroupId != "-1"){//增加
		    let addedDatas=[{"adjId":adjId2,"adjName":adjName,"sceneId":sceneId,"uuid":""}];
		    let addedDataObj={"adjId":adjId2,"adjName":adjName,"sceneId":sceneId,"uuid":""};
        // 保留调整项
	      let reserveDatas=this.reserveAdjDatas;
		    if(reserveDatas.length>0){
          //合并两个数组
          let reserveExist=false;
          let reserveMergeArray =[];
          for(let i=0;i<reserveDatas.length;i++){
            if(reserveDatas[i].adjId==adjId2){
              reserveExist=true;
            }else{
              reserveMergeArray.push(reserveDatas[i]);
            }
          }
          if(!reserveExist){
            reserveMergeArray.push(addedDataObj);
          this.reserveAdjDatas= reserveMergeArray;
          }
        }else{
          this.reserveAdjDatas=addedDatas;
        } 
        // 被斥调整项
        let excludeDatas=this.excludeAdjDatas;
        if(excludeDatas.length>0){
          //合并两个数组
            let excludeExist=false;
          let excludeMergeArray =[];
          for(let i=0;i<excludeDatas.length;i++){
            if(excludeDatas[i].adjId==adjId2){
              excludeExist=true;
            }else{
              excludeMergeArray.push(excludeDatas[i]);
            }
          }
          if(!excludeExist){
            excludeMergeArray.push(addedDataObj);
            this.excludeAdjDatas= excludeMergeArray;
          }
        }else{
            this.excludeAdjDatas=addedDatas;
        } 
 
		} else {//移除
      // 保留调整项 
			let reserveDatas2= this.reserveAdjDatas;
			if(reserveDatas2.length>0){
				//合并两个数组
				let reserveMergeArray2 =[];
				for(let j=0;j<reserveDatas2.length;j++){
					if(reserveDatas2[j].adjId!=adjId2){
						reserveMergeArray2.push(reserveDatas2[j]);
					}
				}
				if(reserveMergeArray2.length>0){
					  this.reserveAdjDatas= reserveMergeArray2;
            //编辑的时候 移除已经选中的
            // for(let i =0;i<this.reserveAdjValue.length;i++){
            //   let resAdj = this.reserveAdjValue[i];
            //   if(resAdj == adjId2){
            //     this.reserveAdjValue.splice(adjId2);
            //     this.saveRuleForm.reserveAdj=this.reserveAdjValue.join();
            //     console.log(this.reserveAdjValue,"--this.reserveAdjValue");
            //   }
            // }
				}
			}
      // 被斥调整项	
			let excludeDatas2= this.excludeAdjDatas;
			if(excludeDatas2.length>0){
				//合并两个数组
				let excludeMergeArray2 =[];
				for(let j=0;j<excludeDatas2.length;j++){
					if(excludeDatas2[j].adjId!=adjId2){
						excludeMergeArray2.push(excludeDatas2[j]);
					} 
				}
				if(excludeMergeArray2.length>0){
					 this.excludeAdjDatas= excludeMergeArray2;
           //编辑的时候 移除已经选中的
            // for(let i =0;i<this.excludeAdjValue.length;i++){
            //   let ecAdj = this.excludeAdjValue[i];
            //   if(ecAdj == adjId2){
            //     this.excludeAdjValue.splice(adjId2);
            //     this.saveRuleForm.excludeAdj=this.excludeAdjValue.join();
            //     console.log(this.excludeAdjValue,"--this.excludeAdjValue");
            //   }
            // }
				}
			}
		}
	},


    // 获取历史页面数据
    getTableDataHistory() {
      let params = {
        sceneCode : this.rowHistory.sceneCode,
        page: this.pageH,
        sceneStatus: "0",
        size: this.sizeH,
        ruleType: this.ruleType
      };
      sceneManage.findHistory(params).then((res) => {
        if (res.code == 200) {
          this.tableDataH = res.datas.rows;
          this.totalH = res.datas.total;
        }
      });
    },
    //保存
    saveFunc() {
      this.$refs["saveRuleForm"].validate((valid) => {
        if (valid) {
          //被斥调整项
          let reserveAdjDatas = [];
          let reserveAdjs = this.saveRuleForm.reserveAdj.split(",");
          for(let i = 0;i<reserveAdjs.length;i++){
            let adjId = reserveAdjs[i];
            let obj = this.adjList.filter(function (c) {
              if (c.adjId == adjId) {
                return c
              }
            })
            reserveAdjDatas.push(obj[0]);
          }
          this.saveRuleForm.reserveAdjDatas = reserveAdjDatas;
          //保留调整项
          let excludeAdjDatas = [];
          let excludeAdjs = this.saveRuleForm.excludeAdj.split(",");
          for(let i = 0;i<excludeAdjs.length;i++){
            let obj = {};
            obj = this.adjList.filter(function (c) {
              if (c.adjId == excludeAdjs[i]) {
                return c
              }
            })
            excludeAdjDatas.push(obj[0]);
          }
         this.saveRuleForm.excludeAdjDatas = excludeAdjDatas;
         //priceRuleDatas 定价方法1、 
          let priceRuleDatas = [];
          let methodRuleGroups = this.saveRuleForm.methodRuleGroup;
          for(let i = 0;i<methodRuleGroups.length;i++){
            let obj = {};
            obj.ruleGroupId = methodRuleGroups[i];
            obj.ruleType = "1";
            priceRuleDatas.push(obj);
          }
          //定价曲线2
          let curveRuleGroups = this.saveRuleForm.curveRuleGroup;
          for(let i = 0;i<curveRuleGroups.length;i++){
            let obj = {};
            obj.ruleGroupId = curveRuleGroups[i];
            obj.ruleType = "2";
            priceRuleDatas.push(obj);
          }
          this.saveRuleForm.priceRuleDatas = priceRuleDatas;

          if(this.ruleOperateType=='2'){
            let versionNum = this.saveRuleForm.versionNum;
            this.saveRuleForm.versionNum = versionNum+1;
          }else if(this.ruleOperateType=='1' || this.ruleOperateType=='5'){
            //复制 或者 新增
            this.saveRuleForm.versionNum = 1;
          }
          this.saveRuleForm.adjRuleDatas = this.adjList;
          
          let data = {
            operateType: this.ruleOperateType,
            sceneManage: { ...this.saveRuleForm },
          };
          sceneManage.save(data).then((res) => {
            if (res.code === 200) {
              this.sceneAddAndEditDi = false;
              this.$message.success("保存成功");
              this.searchFunc();
              
            } else {
              this.$message.error(res.message || "保存失败");
            }
          });   
        } else {
          this.$message.warning("请填写正确的信息！");
        }
      });
    },
    // 删除
    delFunc() {
      let selection = this.$refs.multipleTable.selection;
      if (selection.length < 1) {
        return this.$message.warning("请选择要删除的数据");
      }
      this.$confirm("您确定要删除选中数据吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let data = { ids: selection.map((v) => v.sceneId) };
          sceneManage.remove(data).then((res) => {
            if (res.code == 200) {
              this.$message.success("删除成功");
              this.searchFunc();
            } else {
              this.$message.error(res.message || "删除失败");
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    







  }
  

};
</script>


<style lang="scss" scoped>
.buessinessEleTable .el-table__header th {
  /deep/ .cell {
    white-space: nowrap !important;
  }
}

/deep/.el-dialog__body {
  max-height: 400px;
}
.tipMessage {
  line-height: 32px;
  margin-left: 5px;
  color: red;
  font-family: PingFangSC-Medium, PingFang SC;
  font-weight: 500 !important;
  font-size: 12px !important;
}
.selectBox {
  background: url("~@/assets/images/select_btn.gif");
  background-repeat: no-repeat;
  height: 26px;
  width: 23px;
  position: absolute;
  right: 0;
  top: 5px;
  cursor: pointer;
}
.el-popover {
  max-height: 160px;
  overflow: auto;
}
</style>